import {defineStore} from 'pinia'
import axios from 'axios'
import {formatDate, generateNumericUUID, tools, addressMap, message} from '@/utils'

const useMessageStore = defineStore('message', {
    state: () => ({
        messageList: [...message],
        ws: null,
        tools,
        addressMap,
        websocketMap: {},
        loading: false,
        userInfo: null, // 用户信息
        searchType: 3, // 查询类型
    }),
    actions: {
        setSearchType(type) {
            this.searchType = type
        },
        // 用户信息
        setUserInfo(val) {
            this.userInfo = val
        },
        /**
         * @description: 初始化websocket
         * @param scrollToBottom 是否滚动到底部
         */
        initWebSocket(scrollToBottom) {
            if (this.ws) {
                this.ws.close()
            }
            this.ws = new WebSocket('wss://aikp.zhong360.net/myWs')
            this.ws.onmessage = (event) => {
                const msgData = JSON.parse(event.data)
                let currentIndex = 0
                const intervalId = setInterval(() => {
                    if (currentIndex < msgData.output.text.length) {
                        if (!this.websocketMap[msgData.request_id]) {
                            this.websocketMap[msgData?.request_id] = msgData.request_id
                            this.messageList.push({
                                type: 'AI',
                                message: msgData.output.text[currentIndex],
                                request_id: msgData.request_id
                            })
                        } else {
                            const index = this.messageList.findIndex(item => item.request_id === msgData.request_id)
                            if (index > -1) {
                                this.messageList[index].message += msgData.output.text[currentIndex]
                            }
                        }
                        currentIndex++
                    } else {
                        clearInterval(intervalId)
                    }
                    scrollToBottom && scrollToBottom()
                })
                if (msgData?.output?.finish_reason === 'stop') {
                    this.ws.close()
                    this.ws = null
                }
            }
            this.ws.onopen = () => {
                console.log('WebSocket connected')
            }
            this.ws.onerror = (error) => {
                console.log('WebSocket error:', error)
            }
            this.ws.onclose = () => {
                console.log('WebSocket closed')
                setTimeout(() => {
                    this.initWebSocket(scrollToBottom)
                }, 1000)
            }
        },

        async sendMessage(message, scrollToBottom) {
            console.log('zwthis.searchType', this.searchType)
            try {
                this.messageList.push({type: 'person', message: message})
                console.log('zw1111',)
                if (this.searchType === 1) {
                    await this.getMessages(message, scrollToBottom)
                    return
                }
                const obj = {
                    flag: this.searchType,
                    messages: [
                        {
                            role: 'user',
                            content: message,
                        }
                    ],
                    "stream": true,
                    "userId": this.userInfo?.id || generateNumericUUID(),
                }
                console.log('zwobj', obj)
                this.ws.send(JSON.stringify(obj))
                await scrollToBottom()

            } catch (error) {
                console.log('messageList send error')
            }
        },

        async getMessages(message, scrollToBottom) {
            try {
                this.loading = true
                const res = await axios.post('/llm/invoke',
                    {
                        flag: this.searchType,
                        messages: [
                            {
                                role: 'user',
                                content: message,
                            }
                        ],
                        tools: this.tools,
                        stream: false,
                        // userId: this.userInfo?.id || generateNumericUUID(),
                        userId: this.userInfo?.id || '',
                    })
                if (res?.data?.data) {
                    this.messageList.push({
                        type: 'AI',
                        message: res.data.data?.funArgs ? this.formatAddress(res.data.data.funArgs) : res.data.data.content,
                        isFlow: !!res.data.data?.funArgs,
                        pageArgs: res?.data?.data?.pageArgs || []
                    })
                }
                this.loading = false
                await scrollToBottom()
                return res
            } catch (error) {
                console.log('messageList fetch error')
            }
        },
        formatAddress(funArgs) {
            const arr = []
            for (const key in funArgs) {
                if (this.addressMap.hasOwnProperty(key)) {
                    arr.push(this.addressMap[key] + '：' + funArgs[key])
                }
            }
            return arr.join('</br>')
        },
    }
})

export default useMessageStore

